package com.ganzi.manager.shiro.filter;

import com.ganzi.manager.shiro.redis.ShiroSessionManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 自定义过滤器 处理post请求  前的预处理问题 预处理不会携带token   继承认证拦截器
 * */
public class MyShiroFilterForCors extends FormAuthenticationFilter {
    private static Logger logger = LoggerFactory.getLogger(MyShiroFilterForCors.class);
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (request instanceof HttpServletRequest) {
            if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
                return true;
            }
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
            throws Exception {
        String id = WebUtils.toHttp(request).getHeader(ShiroSessionManager.AUTHORIZATION);
        //登陆身份验证失败后，当发现存在token,说明是ajax访问的，那就不跳转到错误页面，直接返回状态
        if(StringUtils.isNotBlank(id)){
            //aiax验证失败后返回状态不跳转
            WebUtils.toHttp(response).sendError(4001,"Token异常，登陆失败！");
            return false;
        }
        return super.onAccessDenied(request, response);
    }
}
